<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Worker线程学习</title>
    <!-- 
        https://zhuanlan.zhihu.com/p/79484282
     -->
</head>

<body>
    <div>
        Worker 输出内容：<span id='app'></span>
        <input type='text' id='msg'>
        <button onclick='sendMessage()'>发送</button>
        <button onclick='stopWorker()'>stop!</button>
    </div>

    <script type='text/javascript'>
        if (typeof (Worker) === 'undefined')	// 使用Worker前检查一下浏览器是否支持
            document.writeln(' Sorry! No Web Worker support.. ')
        else {
            window.w = new Worker('js/workerThread1.js')
            // 接收子线程内容
            window.w.onmessage = ev => {
                document.getElementById('app').innerHTML = ev.data
            }
            // 发生错误，终止子线程
            window.w.onerror = err => {
                w.terminate()
                console.log(error.filename, error.lineno, error.message) // 发生错误的文件名、行号、错误内容
            }
            // 发送信息
            function sendMessage() {
                const msg = document.getElementById('msg')
                window.w.postMessage(msg.value)
            }
            // 停止子线程
            function stopWorker() {
                window.w.terminate()
            }
        }
    </script>
</body>

</html>